package cn.com.dao.impl;

import cn.com.dao.UserDao;
import cn.com.domain.User;
import cn.com.utils.JDBCutils;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class UserDaoImpl implements UserDao {

    @Override
    public List<User> findAll() {
        List<User> list=new ArrayList<>();
        try {
            Connection conn= JDBCutils.getConnection();
            String sql="select * from user";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            while (rs.next()){
                //封装对象并添加到list集合
                User user=new User();
                String username=rs.getString("username");
                String password=rs.getString("password");
                user.setUsername(username);
                user.setPassword(password);
                list.add(user);
            }
            JDBCutils.close(rs,stmt,conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return list;
    }

    @Override
    //通过名字和密码查找用户
    public User findUserBynameAndPassword(String username, String password) {
        User user=null;
        try {
            Connection conn= JDBCutils.getConnection();
            String sql="select * from user where username = ? and password = ?";
            PreparedStatement pst=conn.prepareStatement(sql);
            pst.setString(1,username);
            pst.setString(2,password);
            ResultSet rs = pst.executeQuery();
            //如果查到了就封装为对象
            if (rs.next()){
                 user=new User(username,password);
            }
            //释放资源
            JDBCutils.close(rs,pst,conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return user;
    }

    @Override
    //添加用户
    public void addUser(User user) {
        try {
            //获取连接并把user插入数据库中的user表
            Connection conn = JDBCutils.getConnection();
            String sql="insert into user values(?,?)";
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1,user.getUsername());
            pst.setString(2,user.getPassword());
            //执行sql语句
            pst.executeUpdate();
            //释放资源
            JDBCutils.close(pst,conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    @Override
    public void delteUser(User user) {
        try {
            Connection conn= JDBCutils.getConnection();
            String sql="delete from user where username = ? and password = ?";
            PreparedStatement pst = conn.prepareStatement(sql);
            pst.setString(1,user.getUsername());
            pst.setString(2,user.getPassword());
            pst.executeUpdate();
            JDBCutils.close(pst,conn);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
